﻿using System;

using System.Data.Entity;
using System.Linq;

using SmallShop.Core;

namespace SmallShop.Dal
{
    public class DefaultDataAccess: IDataAccess
    {
        private readonly ShopDbContext _shopContext;
        public DefaultDataAccess(string connectionName = "default")
        {
            _shopContext = new ShopDbContext(connectionName);
        }


        public IQueryable<T> Query<T>() where T: BaseModel
        {
            return _shopContext.Set<T>().Where(it => it.IsDelete == false);
        }

        public void Add<T>(T model) where T : BaseModel
        {
            model.CreateTime = model.LastUpdateTime = DateTime.Now;
            _shopContext.Set<T>().Add(model);
            //_shopContext.Entry(model).State = EntityState.Added;
        }

        public void Update<T>(T model) where T : BaseModel
        {
            model.LastUpdateTime = DateTime.Now;
            _shopContext.Entry(model).State= EntityState.Modified;
        }

        public void Delete<T>(T model) where T : BaseModel
        {
            model.IsDelete = true;
            _shopContext.Entry(model).State = EntityState.Modified;
        }

        public void SaveChange()
        {
            _shopContext.SaveChanges();
        }
    }
}
